package com.ruralflow.system.service.impl;

import com.ruralflow.system.service.ITess4jService;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;

/**
 * @author bairimengchang
 * @version 1.0
 * @project java-test
 * @description 封装tess4j图像识别服务的api接口实现类
 * @date 2025/3/13
 */
@Service
@Slf4j
public class Tess4JServiceImpl implements ITess4jService {

    /**
     * Tesseract对象（可用来调用doOCR方法操作）
     */
    @Autowired
    private ITesseract tesseract;

    /**
     * OCR图像识别
     * @param multipartFile 文件
     * @return 识别的文字字符串
     */
    @Override
    public String imageToText(MultipartFile multipartFile) {
        // 检查文件是否为空
        if (multipartFile.isEmpty()) {
            throw new RuntimeException("上传的文件为空");
        }

        // 获取上传文件的原始文件名和扩展名
        String originalFilename = multipartFile.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            throw new RuntimeException("上传的文件名为空");
        }
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

        File tempFile = null;
        try {
            // 1. 将 MultipartFile 转换为 Base64 字符串
            byte[] fileBytes = multipartFile.getBytes();
            String base64String = Base64.getEncoder().encodeToString(fileBytes);

            // 2. 将 Base64 字符串解码为临时文件
            byte[] decodedBytes = Base64.getDecoder().decode(base64String);
            tempFile = File.createTempFile("ocr-", fileExtension);
            Files.write(tempFile.toPath(), decodedBytes);

            // 3. 检查文件是否成功写入
            if (!tempFile.exists() || tempFile.length() == 0) {
                throw new RuntimeException("文件写入失败");
            }

            // 4. 进行 OCR 识别
            long startTime = System.currentTimeMillis();
            String result = tesseract.doOCR(tempFile);
            result = result.replaceAll("\\s+", ""); // 去除所有空格
            long endTime = System.currentTimeMillis();
            log.info("共耗时：{} 毫秒", endTime - startTime);

            log.info("图片转文字结果：{}", result);
            return result;
        } catch (IOException | TesseractException e) {
            log.error("图片转文字失败", e);
            throw new RuntimeException(e);
        } finally {
            // 5. 确保临时文件被删除
            if (tempFile != null && tempFile.exists()) {
                boolean deleted = tempFile.delete();
                log.info("临时文件删除结果：{}", deleted);
                if (!deleted) {
                    log.warn("临时文件删除失败: {}", tempFile.getAbsolutePath());
                }
            }
        }
    }

}
